<template>
    <div>
      <div class="wordcloud-chart" ref='wordcloudchart'>
        <canvas v-if="isHasData" class="wordcloud__container" width="980" height="1000" style="width:490px;height:500px;"></canvas>
        <div v-else class="empty">暂无数据</div>
      </div>
      <section class="word-times-tip" v-if="activeWord" :style="wordTipStyle">
    “{{ activeWord.word }}”被提到了{{ activeWord.num }}次</section>
    </div>
</template>
<style lang="scss">
.empty{
    text-align:center;
    width:100%;
    height:100%;
    color:#ccc;
    font-size:13px;
}
.wordcloud-chart {
    position: relative;
    flex: 1;

    display: flex;
    justify-content: center;
    align-items: center;

    padding: 0px;
}
.wordcloud__container {
    position: relative;
    display:block;
    margin:0 auto;
    width:490px;
    height:500px;
    // min-width: 75vw;
    // max-height: calc(100% - 100px);

    cursor: pointer;
}
.word-times-tip {
    position: fixed;
    left: 0;
    top:0;
    z-index:1000;
    background:#fff;
    text-align: center;
    padding: 10px 10px;
    border-radius: 3px;
    box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.1);
  }
</style>
<script>
let wordcloud = require('wordcloud');
const colors = [
  '#FFE0D0',
  '#AED9E0',
  '#D9E8FA',
  '#E1938A',
  '#EEEEEE',
  '#CEBAA1',
  '#BBB0D2',
  '#8CA7B6',
  '#C24B4C'
];
export default {
  props: ['chartData'],
  data(){
    return {
       isHasData: false,
       activeWord:null,
       wordTipStyle: 'top:0px;left:0px;'
    }
  },
  computed: {
    element () {
      return this.$refs.wordcloudchart
    }
  },
  methods: {
    renderChart () {
      this.isHasData = (Object.prototype.toString.call(this.chartData) == "[object Array]" && this.chartData.length > 0) ? true : false;
       this.$nextTick(() => {
          if (Object.prototype.toString.call(this.chartData) == "[object Array]" && this.chartData.length > 0) {
            var list = this.formatData(this.chartData);
            this.createWordcloud(list);
            //this.testWordcloud();
          }
       });
    },
    /**
     * @method 生成词云
     * @params
     */
    createWordcloud(list) {
      var canvasEl = $(this.element).find(".wordcloud__container")[0];
      let options = {
        gridSize: 32,
        weightFactor: 6,
        shrinkToFit: true,
        fontFamily: '"Helvetica Neue","PingFang SC","Microsoft YaHei",sans-serif',
        // backgroundColor: '#284D83',
        backgroundColor: 'transparent',
        list: list,
        color: (word, weight, fontSize, distance, theta) => {
          let index = Math.floor(Math.random()*9);
          let color = colors[index];
          return color;
        },
        hover: (item, dimension, event) => {
          var clientX = event.clientX || event.screenX || event.x;
          var clientY = event.clientY || event.screenY || event.y;
          this.wordTipStyle = 'left:' + (clientX+20) + 'px;top:' + (clientY-50) + 'px';
          if(item && item[0]) {
            this.activeWord = {
              word: item[0],
              num: parseInt(item[2])
            };
          }

        },
        click: (item) => {
          
        },
      };
      if(canvasEl && canvasEl.nodeType == 1 && canvasEl.tagName.toLowerCase() == "canvas"){
        wordcloud(canvasEl, options);
      }
    },
    /**
     * @method 格式化数据
     * @params
     */
    formatData(list) {
      let minFontSize = 20;
      let maxFontSize = 60;

      if(list.length > 80) {
        minFontSize = 6;
        maxFontSize = 20;
      }else if(list.length > 50) {
        minFontSize = 14;
        maxFontSize = 40;
      } else if(list.length > 30) {
        minFontSize = 20;
        maxFontSize = 50;
      } 
      
      let len = list.length;
      let maxCount = parseInt(len && list[0].weight*100 || 0, 10);
      let minCount = parseInt(len && list[len - 1].weight*100 || 0, 10);

      return list.map((item)=>{
        let num = parseInt(item.weight*100 / maxCount * maxFontSize, 10);
        num = Math.max(num, minFontSize);
        return [ item.word, num, item.weight*100 ]
      })
    },
    testWordcloud() {
      let data  = [
        {"num":34,"word":"毛泽东思想"},
        {"num":25,"word":"汇报"},
        {"num":21,"word":"图书馆"},
        {"num":20,"word":"管理员"},
        {"num":19,"word":"邓小平理论"},
        {"num":16,"word":"伟大旗帜"},
        {"num":15,"word":"完美"},
        {"num":13,"word":"世界"},
        {"num":12,"word":"排行榜"},
        {"num":10,"word":"小说"},
      ];

      var list = this.formatData(data);
      setTimeout(()=>{
        this.createWordcloud(list);
      }, 100)
    }
  },
  watch:{
    chartData:{
      handler(newVal){
        this.renderChart()
      },
      deep: true
    }
  },
  mounted() {
    this.isHasData = (Object.prototype.toString.call(this.chartData) == "[object Array]" && this.chartData.length > 0) ? true : false;
    this.$nextTick(() => {
      this.renderChart();
      $(".wordcloud-chart").on("mouseout", ()=>{
        this.activeWord = null;
      });
    })
  }
}
</script>


